﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MapObjects;
using System.IO;

namespace MOClient
{
    public partial class SelectByAttributesForm : Form
    {
        Layers layers;
        Recordset prevRecs;
        public Form mForm;
        public Recordset glrecs;


        public SelectByAttributesForm()
        {
            InitializeComponent();
        }

        public SelectByAttributesForm(Layers l, Form f)
        {
            InitializeComponent();
            layers = l;
            mForm = f;
            layerComboBox.Items.Clear();
            for (int i = 0; i < layers.Count; ++i)
            {
                layerComboBox.Items.Add(((MapLayerClass)layers.Item(i)).name);
            }
            layerComboBox.SelectedIndex = 0;
            methodComboBox.SelectedIndex = 0;
        }

        private void SelectByAttributesForm_Load(object sender, EventArgs e)
        {

        }

        private void layerComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            attrListBox.Items.Clear();
            expressionTextBox.Clear();
            attrListBox.Items.Add("\"FID\"");
            for (short i = 0; i < ((MapLayerClass)layers.Item(layerComboBox.SelectedIndex)).Records.TableDesc.FieldCount; ++i)
            {
                attrListBox.Items.Add("\"" + ((MapLayerClass)layers.Item(layerComboBox.SelectedIndex)).Records.TableDesc.get_fieldName(i) + "\"");
            }
            selLabel.Text = "SELECT * FROM " + ((MapLayerClass)layers.Item(layerComboBox.SelectedIndex)).name + " WHERE: ";
        }

        private void attrListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            expressionTextBox.Text += ((ListBox)sender).SelectedItem.ToString() + " ";
        }

        private void expressionTextBox_TextChanged(object sender, EventArgs e)
        {
            if (((TextBox)sender).Text.Equals(""))
            {
                clearButton.Enabled = false;
            }
            else
            {
                clearButton.Enabled = true;
            }
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Clear();
        }

        #region save / load
        private void saveButton_Click(object sender, EventArgs e)
        {
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK
                && !saveFileDialog.FileName.Equals(""))
            {
                StreamWriter s = new StreamWriter(saveFileDialog.FileName);
                s.Write(expressionTextBox.Text);
                s.Close();
            }
        }

        private void loadButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog(this) == DialogResult.OK
                && !openFileDialog.FileName.Equals(""))
            {
                StreamReader s = new StreamReader(openFileDialog.FileName);
                expressionTextBox.Text = s.ReadToEnd();
                s.Close();
            }
        }
        #endregion

        #region ok / cancel
        private void closeButton_Click(object sender, EventArgs e)
        {
            Hide();
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            ApplySelection(methodComboBox.SelectedIndex);
            Hide();
        }
        #endregion

        #region expression builder
        private void eqButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "= ";
        }

        private void notEqButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "<> ";
        }

        private void greaterButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "> ";
        }

        private void greaterEqButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += ">= ";
        }

        private void lessButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "< ";
        }

        private void lessEqButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "<= ";
        }

        private void unLineButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "_ ";
        }

        private void modButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "% ";
        }

        private void parButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "() ";
        }

        private void isButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "IS ";
        }

        private void notButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "NOT ";
        }

        private void orButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "OR ";
        }

        private void andButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "AND ";
        }

        private void likeButton_Click(object sender, EventArgs e)
        {
            expressionTextBox.Text += "LIKE ";
        }
        #endregion

        String StripQuotes(String str)
        {
            return str.Substring(1, str.Length - 2);
        }

        private void getValsButton_Click(object sender, EventArgs e)
        {
            MapLayer ml = ((MapLayerClass)layers.Item(layerComboBox.SelectedIndex));
            Recordset recs = ml.Records;
            List<String> vals = new List<String>();

            valsListBox.DataSource = null;
            valsListBox.Items.Clear();
            valsListBox.Enabled = true;
            recs.MoveFirst();

            if (attrListBox.SelectedIndex == -1)
                return;

            while (!recs.EOF)
            {
                String fld = StripQuotes(attrListBox.SelectedItem.ToString());
                try
                {
                    vals.Add(recs.Fields.Item(fld).Value.ToString());
                }
                catch (Exception)
                {
                }
                recs.MoveNext();
            }

            vals.Sort();
            valsListBox.DataSource = vals.Distinct().ToList();            
        }

        private void attrListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            valsListBox.Enabled = false;
        }

        private void valsListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // DUMMY!
            Int32 dummy1;
            Double dummy2;
            if (Int32.TryParse(valsListBox.SelectedItem.ToString().Trim(), out dummy1)
                || Double.TryParse(valsListBox.SelectedItem.ToString().Trim(), out dummy2))
            {
                expressionTextBox.Text += ((ListBox)sender).SelectedItem.ToString() + " ";
            }
            else
            {
                expressionTextBox.Text += "'" + ((ListBox)sender).SelectedItem.ToString() + "' ";
            }
        }

        private Recordset GetSelection(Int32 idx)
        {
            MapLayer ml = ((MapLayerClass)layers.Item(layerComboBox.SelectedIndex));
            Recordset recs = ml.SearchExpression(expressionTextBox.Text.Trim());
            return recs;
        }

        private void ApplySelection(Int32 idx)
        {
            glrecs = GetSelection(idx);
            mForm.Focus();
            ((MainForm)mForm).axMap1.Refresh();
        }

        private void applyButton_Click(object sender, EventArgs e)
        {
            ApplySelection(methodComboBox.SelectedIndex);
        }
    }
}
